package com.mud.mudcommune.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * Created by welcome to china on 2016/12/10.
 */

public class PinyinUtils {
    private static char aChar;

    public static String getPinyin(String hanzi){
        String result="";
        HanyuPinyinOutputFormat hanyuPinyinOutputFormat=new HanyuPinyinOutputFormat();
        hanyuPinyinOutputFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        hanyuPinyinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        char[] chars = hanzi.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char ch=chars[i];
            if(Character.isWhitespace(ch)){
                continue;
            }
            if(ch>127){//只能理论上面说是一个汉字
                try {
                    String[] strings = PinyinHelper.toHanyuPinyinStringArray(ch, hanyuPinyinOutputFormat);
                    if(ch=='长'){
                        strings[0]="Chang";//只有长字出错  没办法的办法
                    }
                    if(strings==null){
                        result+=ch;
                    }else{
                       result+=strings[0];//如果是多音字的话就拿第一个
                    }
                } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                    badHanyuPinyinOutputFormatCombination.printStackTrace();
                    result+=ch;
                }
            }
        }
        return result;
    }
}
